package com.rt.cloud.auth.config;

import com.rt.easyjava.common.base.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.web.client.RestTemplate;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class JwtTokenConfig {

    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyPair());
        return converter;
    }


    @Bean
    public KeyPair keyPair() {
        KeyStoreKeyFactory keyFactory = new KeyStoreKeyFactory(new ClassPathResource("oauth2.jks"), "oauth2".toCharArray());
        return keyFactory.getKeyPair("oauth2", "oauth2".toCharArray());
    }

    /*@Bean
    public ResourceServerTokenServices resourceJwtTokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        // 使用自定义的Token转换器
        defaultTokenServices.setTokenEnhancer(jwtAccessTokenConverter());
        // 使用自定义的tokenStore
        defaultTokenServices.setTokenStore(jwtTokenStore());
        return defaultTokenServices;
    }
    */

    @Autowired
    private RestTemplate restTemplate;

    /**
     * token信息扩展
     */
    @Bean
    public TokenEnhancer jwtTokenEnhancer() {
        return new TokenEnhancer() {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                Authentication userAuthentication = authentication.getUserAuthentication();
                if (userAuthentication != null) {
                    String userName = userAuthentication.getName();

                    Result result = restTemplate.getForObject("http://scm-epcodeless-core/core/innerService/getUserByLoginName/"+userName, Result.class);

                    Map<String, Object> userMap = (Map<String, Object>)result.getObj();
                    if(userMap == null){
                        throw new UsernameNotFoundException("用户不存在！");
                    }
                    List<String> authList = (List<String>) userMap.get("menu2AuthList");
                    Map<String, Integer> dataLimitMap = (Map<String, Integer>) userMap.get("dataLimitMap");

                    Map<String, Object> additionalInformation = new HashMap<>();
                    Map<String, Object> map = new HashMap<>();
                    map.put("userId", userMap.get("id"));
                    map.put("loginName", userMap.get("loginName"));
                    map.put("name", userMap.get("name"));
                    map.put("createTime", userMap.get("createDateStr"));
                    int deleteFlag = userMap.get("deleteFlag")==null?0:(Integer) ((Integer) userMap.get("deleteFlag")).intValue();
                    boolean state = deleteFlag==0 ? true: false;
                    map.put("state", state);
                    // 机构 部门 信息
                    Integer instituteId = (Integer)userMap.get("instituteId");
                    map.put("instituteId", instituteId);
                    map.put("instituteCode", userMap.get("instituteCode"));
                    map.put("instituteName", userMap.get("instituteName"));
                    map.put("departmentId", userMap.get("departmentId"));
                    map.put("departmentCode", userMap.get("departmentCode"));
                    map.put("departmentName", userMap.get("departmentName"));
                    // 该机构负责的值勤区域 单独提供接口调用，避免业务和认证接口混合
                    /*Result resultDutyArea = restTemplate.getForObject("http://resource-city/city/coding/ctcDutyArea/selectByInstituteId/"+instituteId, Result.class);
                    System.out.println("resultDutyArea.isSuccess(): "+resultDutyArea.isSuccess());
                    List<Map<String, Object>> dutyAreaList = resultDutyArea.getList();
                    System.out.println(dutyAreaList);*/

                    additionalInformation.put("user", map);// JSON.toJSONString(map));
                    additionalInformation.put("dataLimitMap", dataLimitMap);// JSON.toJSONString(map));
                    //additionalInformation.put("dutyAreaList", dutyAreaList);
                    additionalInformation.put("authorities", authList);
                    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
                }
                return accessToken;
            }
        };
    }
}
